<?php
Loader::loadClass('AntiSpam', "modules/InnoForum/pnincludes");

class PNUserPosts extends PNObjectEx {
  function PNUserPosts($init=null, $where='')
  {
    $this->PNObject();
    $this->_objType       = 'innoforum_posts';
    $this->_objField      = 'id';
    $this->_objPath       = 'form';

    $this->_init($init, $where);

  }

  function validate(){
    $form = FormUtil::getPassedValue ('form', false);
    $is_loggedin = pnUserLoggedIn();
    $is_validate = true;
    if (!$is_loggedin) {
      $valid = pnModAPIFunc('InnoForum', 'user', 'checkCaptchaCode',array('code' => $form['captcha']));

      if($valid == true) {
        SessionUtil::delVar('YLERROR');
        $is_validate = true;
      }else{
        $error = "ขออภัย รหัสยืนยันไม่ถูกต้องโปรดกรอกใหม่อีกครั้ง";
        SessionUtil::setVar('YLERROR', $error, '/', true, true);
      
        $is_validate = false;
      }
    }

    $wc = AntiSpam::str_match_count('href',$form['detail']);
    if ($wc  > 0){
      $error = "ขออภัย ห้ามใส่ลิงค์ครับ";
      SessionUtil::setVar('YLERROR', $error, '/', true, true);
      $is_validate = false;
    }

    return $is_validate;
  }

  function addCountPost(){
    $form = FormUtil::getPassedValue ('form', false);
    $id =  $form['topics_id'];
    if ($id){
      $where = 'tpc_id = '.$id;
      //$max = DBUtil::selectFieldMax('innoforum_posts', 'topics_id', 'MAX', $where_post_topics_id);
      $count_post = DBUtil::selectObjectCount( 'innoforum_posts', 'pst_topics_id = '.$id, 'id', true, null);
      //$count_post = DBUtil::selectFieldByID( 'innoforum_topics', 'count_post', $id);
      $object = array('count_post'=>$count_post);
      DBUtil::updateObject($object, 'innoforum_topics', $where);
    }
  }

  function delCountPost(){
    $id = FormUtil::getPassedValue ('id', false);
    if ($id){
      $max = DBUtil::selectFieldMax('innoforum_topics','count_post');
      $object = array('id'=>$id , 'count_post'=>intval($max) - 1);
      DBUtil::updateObject($object,'innoforum_topics');
    }
  }

  function uploadFiles($id){
    $topics_id = DBUtil::selectFieldByID( 'innoforum_posts', 'topics_id', $id);
    $count_topics = DBUtil::selectObjectCount('innoforum_resource_image' , "WHERE rsi_referer_id = '$topics_id' AND rsi_path = 'topics'");
    $count_posts = DBUtil::selectObjectCount('innoforum_resource_image' , "WHERE rsi_referer_id = '$topics_id' AND rsi_path = 'posts'");
    $count = $count_topics+$count_posts;

    if ($id && $_FILES['images']['error'] === 0){
      $images = $_FILES['images'];

      //Set directory to store image path
      $imagespathbyid = "resource/innoforum_upload/large/".$topics_id."/posts/";
      $thumbspathbyid = "resource/innoforum_upload/medium/".$topics_id."/posts/";
      //Make topic image directory by id
      if (!is_dir($imagespathbyid)) {
        mkdir($imagespathbyid, 0777);
      }
      //Make topic thumb directory by id
      if (!is_dir($thumbspathbyid)) {
        mkdir($thumbspathbyid, 0777);
      }

      //Set directory to store image path by id
      $imagespath = $imagespathbyid.$id."/";
      $thumbspath = $thumbspathbyid.$id."/";
      //Make topic image directory by id
      if (!is_dir($imagespath)) {
        mkdir($imagespath, 0777);
      }
      //Make topic thumb directory by id
      if (!is_dir($thumbspath)) {
        mkdir($thumbspath, 0777);
      }

        if ($error == 0){
            //Gennerate next id
            $image_id = DBUtil::selectFieldMax( 'innoforum_resource_image', 'id', 'MAX', '');
            if($image_id == null){
              $next_id = 1;
            }else{
              $next_id = $image_id+1;
            }

            $tmp_name = $images["tmp_name"];
            $fliename = $images["name"];
            $filetype = $images["type"];
            $filesize = $images["size"];

////////////////////////// get the extension of the file in a lower case format/////////////////////////////////////////////
            $filename = stripslashes($fliename);
            $i = strrpos($filename,".");
            if (!$i) { return ""; }
            $l = strlen($filename) - $i;
            $ext = substr($filename,$i+1,$l);
            $extension = strtolower($ext);

////////////////////////////generate new file&path/////////////////////////////////////////////////////////////////////
            $rootname       = $next_id.time().".".$extension;
            $filename_temp  = "ipost_".$id.$rootname;
            $thumbname_temp = "tpost_".$id.$rootname;
            $imgpath        = $imagespath.$filename_temp;
            $tmbpath        = $thumbspath.$filename_temp;
            $originalImagePath = $imagespath.$fliename;



//////////////////////////start upload/////////////////////////////////////////////

        $source = $tmp_name;
        $target = $imgpath;
        move_uploaded_file($source, $target);

        //images
        $imagepath = $fliename;
        $save = $imgpath;; //This is the new file you saving
        $file = $imgpath; //This is the original file
        list($width, $height) = getimagesize($file) ; 

//////////////////resize image orginal////////////////////
        $modwidth = 600; 
        $diff = $width / $modwidth;
        if (($width > 600) || ($height > 200)) 
        {
          $modheight = $height / $diff; 
          $tn = imagecreatetruecolor($modwidth, $modheight); 
          if($filetype == "image/pjpeg" || $filetype == "image/jpeg"){
            $image = imagecreatefromjpeg($file) ; 
          }elseif($filetype == "image/x-png" || $filetype == "image/png"){
            $image = imagecreatefrompng($file) ;
          }elseif($filetype == "image/gif"){
            $image = imagecreatefromgif($file) ;
          }
            imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; 
        }

        if($filetype == "image/pjpeg" || $filetype == "image/jpeg"){
          imagejpeg($tn, $save, 100) ; 
        }elseif($filetype == "image/x-png" || $filetype == "image/png"){
          imagepng($tn, $save) ; 
        }elseif($filetype == "image/gif"){
          copy($file, $save) ; 
        }

//////////////////resize image thumb////////////////////

        $save = $tmbpath; //This is the new file you saving
        $file = $imgpath; //This is the original file

        list($width, $height) = getimagesize($file) ; 

        $modwidth = 100; 
        $diff = $width / $modwidth;
        $modheight = $height / $diff; 
        $tn = imagecreatetruecolor($modwidth, $modheight); 
        if($filetype == "image/pjpeg" || $filetype == "image/jpeg"){
          $image = imagecreatefromjpeg($file) ; 
        }elseif($filetype == "image/x-png" || $filetype == "image/png"){
          $image = imagecreatefrompng($file) ;
        }elseif($filetype == "image/gif"){
          $image = imagecreatefromgif($file) ;
        }
        imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; 

        if($filetype == "image/pjpeg" || $filetype == "image/jpeg"){
          imagejpeg($tn, $save, 100) ; 
        }elseif($filetype == "image/x-png" || $filetype == "image/png"){
          imagepng($tn, $save) ; 
        }elseif($filetype == "image/gif"){
          copy($file, $save) ; 
        }

            $objects = array(
                            'id'         => $next_id,
                            'path'       => 'posts',
                            'referer_id' => $topics_id,
                            'filename'   => $filename_temp,
                            'filesize'   => $filesize,
                            'filetype'   => $filetype,
                            'thumbname'  => $filename_temp,
                            'thumbsize'  => $thumbsize,
                            'thumbtype'  => $thumbtype
                           );

            DBUtil::insertObject($objects,'innoforum_resource_image');

            $objects = array(
                            'filename'   => $filename_temp,
                            'thumbname'  => $filename_temp
                           );

            $where = "WHERE pst_id = '$id' AND pst_topics_id = '$topics_id'";
            DBUtil::updateObject($objects,'innoforum_posts',$where);

        }
      }

  }

  function insertPreProcess(){
    $this->_objData['ipaddress'] = InnoUtil::getIpAddress();
    if ($_FILES['images']['error'] === 0){
      $this->_objData['has_image'] = 'T';
    }
  }

  function insertPostProcess(){
     $topics_id = $this->_objData['topics_id'];
     $post_id = $this->_objData['post_id'];
     $new_detail = $this->_objData['detail'];
    if ($post_id){
      $where = 'pst_id = '.$post_id;
      $old_detail = DBUtil::selectObject( 'innoforum_posts', $where, array('id','detail'));
      $detail = $old_detail['detail']."<br /><br /><img src='modules/InnoForum/pnimages/comments.png' align='absmiddle'> ความคิดเห็นเพิ่มเติมวันที่ ".date("j F Y เวลา G.i a", time())."<br /><hr />".$new_detail;
      $object = array('detail'=>$detail);
      DBUtil::updateObject($object, 'innoforum_posts', $where);

      $where = " pst_topics_id = ".$topics_id;
      $pstid = DBUtil::selectFieldMax('innoforum_posts', 'id', 'MAX', $where);
      DBUtil::deleteObjectByID( 'innoforum_posts', $pstid, 'id');

    }else{
      $id = DBUtil::getInsertID ($this->_objType, $this->_objField);
      $this->uploadFiles($id);
     }
      $this->addCountPost();
      $this->sendmail();

  }


  function updateCountPost(){
    $topic_id = FormUtil::getPassedValue ('topic_id', false);
    //Delete count post
    $where = ' tpc_id = '.$topic_id;
    $count_post = DBUtil::selectObjectCount( 'innoforum_posts', 'pst_topics_id = '.$topic_id, 'id', true, null);
    $object = array('count_post'=>$count_post);
    DBUtil::updateObject($object, 'innoforum_topics', $where);

  }

  function updatePostProcess(){
      $this->addCountPost();

  }


  function deletePreProcess(){
    $id        = FormUtil::getPassedValue ('id', false);
    $topic_id = FormUtil::getPassedValue ('topic_id', false);

    if($id && $topic_id ){
      //Set directory to store image path
      $images_post_path = "resource/innoforum_upload/large/".$topic_id."/posts/".$id;
      $thumbs_post_path = "resource/innoforum_upload/medium/".$topic_id."/posts/".$id;

      $this->deleteDirectory($images_post_path);
      $this->deleteDirectory($thumbs_post_path);

      //delete post
      //DBUtil::deleteWhere('innoforum_posts',"WHERE pst_topics_id = '$topic_id'");
      //DBUtil::deleteWhere('innoforum_resource_image',"WHERE rsi_referer_id = '$topic_id' AND rsi_path = 'posts' AND rsi_id = '$id'");
    }

  }
  
  function deleteDirectory($dirname) {
    if (is_dir($dirname))
       $dir_handle = opendir($dirname);
    if (!$dir_handle)
       return false;
    while($file = readdir($dir_handle)) {
       if ($file != "." && $file != "..") {
          if (!is_dir($dirname."/".$file))
             unlink($dirname."/".$file);
          else
             $this->deleteDirectory($dirname.'/'.$file);    
       }
    }
    closedir($dir_handle);
    rmdir($dirname);
    return true;
  }

  function deletePostProcess(){
    $this->updateCountPost();
  }

  function sendmail(){
    $form = $form = FormUtil::getPassedValue ('form', false);
    $id =  $form['topics_id'];
    
    $object = DBUtil::selectObjectByID('innoforum_topics',$id);

    $email = $object['email'];
    $is_sendmail = $object['is_sendmail'];
    
    //check if topics creator and poster is same,not send email
    $post_uid = pnUserGetVar('uid');
    $is_same_post = $object['cr_uid'] == $post_uid ? true : false;
    if ($is_sendmail && !empty($email) && $object && !$is_same_post){
        //load language
        Loader::loadFile('user.php', 'modules/InnoForum/pnlang/eng' );

        $render = pnRender::getInstance('InnoForum');
        $render->assign('posts_id',$this->_objData['id']);
        $render->assign('topics_id',$object['id']);
        $render->assign('topics_title',$object['title']);
        $message = $render->fetch('users_email_anstopics.htm');
        //$message = iconv('TIS-620','UTF-8',$message);

        $subject = pnML('_EMAIL_SUBJECT',array('sitename'=> pnConfigGetVar('sitename')));
        if($message && strlen($message)){
          $result = pnModAPIFunc('Mailer', 'user', 'sendmessage', 
                      array('toaddress' => $email, 
                      'subject' => $subject, 
                      'body' => $message, 
                      'html' => true,
                      'charset' => 'UTF-8'));
        }
    }
  }
}